<template>
  <div class="data-upload-preview-wrapper" :class="{'data-upload-preview-wrapper-coordinate': coordinateFieldShow}">
    <div class="dialog">

      <div class="space-field-wrapper" v-if="previewData && coordinateFieldShow">
        <div class="coordinate-type">
          <g-checkbox :model="coordinateChecked" v-on:change="coordinateChecked = !coordinateChecked">选择经纬度字段</g-checkbox>
        </div>
        <div class="coordinate-type-select" v-if="coordinateChecked">
          <label>经度</label>
          <g-select class="fields-select xFields-select" :options="xFields" @option-select="xFieldChange"></g-select>
          <label>纬度</label>
          <g-select class="fields-select yFields-select" :options="yFields" @option-select="yFieldChange"></g-select>
        </div>

        <!-- <div class="coordinate-type">
          <input type="radio" name="type" v-model="spaceType" value="coordinate" id="coordinate">
          <label for="coordinate">选择经纬度字段</label>
          <input type="radio" name="type" v-model="spaceType" value="none" id="none">
          <label for="none">暂不选择</label>
        </div>
        <div class="coordinate-type-select" v-if="spaceType === 'coordinate'">
          <label>经度</label>
          <g-select class="fields-select xFields-select" :options="xFields" @option-select="xFieldChange"></g-select>
          <label>纬度</label>
          <g-select class="fields-select yFields-select" :options="yFields" @option-select="yFieldChange"></g-select>
        </div> -->

      </div>
      <!-- 数据预览 -->
      <div class="preview-table-wrapper" v-if="previewData">
        <table-view :reset="resetTable" :preview-data="previewData" :to-submit-fields="fields" :highLight="[xField,yField]"></table-view>
      </div>

      <!-- 选择编码工具条 -->
      <div class="toolbar" :class=" coordinateFieldShow ? 'toolbar-low': null" v-show="previewData">
        <div class="tip-wrapper">
          <span>若出现乱码请修改编码</span>
        </div>
        <div class="encoding-select-wrapper">
          <g-select class="encoding-select" :options="encodings" :selected-option="selectedOption" :menu-direction="true"
            @option-select="encodingChange"></g-select>
        </div>
      </div>
    </div>

    <!-- 状态标识 -->
    <div class="loading-wrapper" v-show="isLoading">
      <div class="loading">
        <i class="iconfont icon-loading icon-spin"></i>
      </div>
    </div>
  </div>
</template>

<script>
  import TableView from './data-upload-preview-table';
  import GSelect from '@/components/common/g-select';
  import GButton from '@/components/common/g-button';
  import axios from 'axios';
  import qs from 'qs';
  import Bus from '../../utils/event_bus';
  import {
    encodings
  } from '@/config/config';
  import constants from '@/config/constant';
  import {
    job as jobAPI
  } from '@/api';
  import GCheckbox from '../common/g-checkbox'

  const axiosInstance = axios.create();

  export default {
    name: 'upload-preview',
    components: {
      'table-view': TableView,
      'g-select': GSelect,
      'g-button': GButton,
      'g-checkbox': GCheckbox,
    },
    props: {
      uid: String,
      offset: Number,
      encoding: String,
      toPublic: Boolean,
      selectedFile: File,
      fileType: String,
    },
    data() {
      return {
        previewData: null, // 待预览数据
        encodings: encodings,
        selectedEncoding: this.encoding,
        selectedOffset: this.offset,
        publicUpload: this.toPublic,
        selectedOption: null,
        isLoading: false, // 是否显示等待标识
        fields: [], // 数据字段名称及类型
        nextInvalid: false, // 是否允许下一步操作
        loadingFinish: false,
        resetTable: false,
        fieldTypes: [],
        xFields: [],
        yFields: [],
        xField: null,
        yField: null,
        haveSpaceField: false,
        // spaceType: 'coordinate',
        coordinateChecked: false,
      };
    },
    computed: {
      coordinateFieldShow() {
        return this.fileType == 'csv' || this.fileType == 'excel';
      },
    },
    watch: {
      previewData() {
        this.xFields = [];
        this.yFields = [];

        this.coordinateChecked = false;
        Bus.$emit('coordinate-xField', null);
        Bus.$emit('coordinate-yField', null);
        
        let coordinateFields = this.getGeoFields(this.previewData.data);
        for (let xField of coordinateFields.xFields) {
          this.xFields.push({
            value: xField.field,
            label: xField.field
          });
        }
        for (let yField of coordinateFields.yFields) {
          this.yFields.push({
            value: yField.field,
            label: yField.field
          });
        }

      },
      coordinateChecked(val) {
        if (!val) {
          Bus.$emit('coordinate-xField', null);
          Bus.$emit('coordinate-yField', null);
        }
      },
      //   spaceType(val) {
      //     switch (val) {
      //       case 'coordinate':
      //         {
      //           break;
      //         }
      //       case 'none':
      //         {
      //           Bus.$emit('coordinate-xField', null);
      //           Bus.$emit('coordinate-yField', null);
      //           break;
      //         }
      //     }
      //   }
    },
    methods: {
      async getPreviewData() {
        try {
          this.isLoading = true;
          const params = {
            encoding: this.selectedEncoding,
            num: 10
          };
          if (!this.uid) {
            return;
          }
          let result = await axiosInstance.get(`/s/data/${this.uid}/preview`, {
            params: params
          });
          this.isLoading = false;
          if (result.data.data.code == 701) {
            Bus.$emit('preview-data-file-error', constants.uploadErr['555']);
          }
          return result.data.data;
        } catch (ex) {
          Bus.$emit('preview-data-get-error', constants.uploadErr['554']);
        }
      },

      /**
       * @description 用户选择编码事件
       * @param {string} selectedValue 选项索引
       * @param {string} selectedText 选项显示文本
       */
      async encodingChange(selectedValue, selectedText) {
        this.selectedOption = {
          value: selectedValue,
          label: selectedText
        };
        this.selectedEncoding = selectedText;
        this.previewData = await this.getPreviewData();
        this.resetTable = true;
        this.fields = [];
        // 预处理字段重名问题
        for (const [idx, field] of this.previewData.fields.entries()) {
          let fieldNames = [];
          this.previewData.fields.forEach((field) => {
            fieldNames.push(field.name);
          });
          this.previewData.fields[idx].name = this.changeName(fieldNames, field.name);
        }

        this.previewData.fields.forEach(field => {
          this.fields.push(field.name);

          this.fieldTypes.push(-1);
        });
        // 派发改变编码事件
        Bus.$emit('data-upload-change-encoding', this.fields, this.fieldTypes, this.selectedEncoding);
      },

      xFieldChange(selectedValue) {
        this.xField = selectedValue;
        Bus.$emit('coordinate-xField', selectedValue);
      },

      yFieldChange(selectedValue) {
        this.yField = selectedValue;
        Bus.$emit('coordinate-yField', selectedValue);
      },
      /**
       * @description 如果字段中存在重复名称，修改字段名，规则为`现有名称${重复数}`
       * @param {Array} arr 字段名数组
       * @param {String} item 待检测字段名
       * @return {Array} 修改重复字段名称后的数组
       */
      changeName(arr, item) {
        let count = 1;
        let result = item;
        if (arr.indexOf(item) !== arr.lastIndexOf(item)) {
          return this.changeName(arr, item + (++count));
        }
        return result;
      },

      /**
       * 根据字段名称猜测是否是空间字段
       */
      geoFieldTypeByName(fieldName) {
        fieldName = fieldName.toLowerCase();
        const longitude = ['longitude', 'lon', 'lng', 'x', '经度', '_x', '_lng', 'st_x'];
        const latitude = ['latitude', 'lat', 'y', '纬度', '_y', '_lat', 'st_y'];
        if (longitude.includes(fieldName)) {
          return 'xField';
        }
        if (latitude.includes(fieldName)) {
          return 'yField';
        }
        return false;
      },

      /**
       * 猜经纬度字段
       */
      getGeoFields(data) {
        let xFieldO = {};
        let yFieldO = {};
        let xFields = [];
        let yFields = [];
        let haveXFields = false;
        let haveYFields = false;
        //字段名判断
        for (let key in data[0]) {
          xFieldO[key] = 0;
          yFieldO[key] = 0;
          let type = this.geoFieldTypeByName(key);
          if (type === 'xField') {
            xFieldO[key] += 20;
            haveXFields = true;
          };
          if (type === 'yField') {
            yFieldO[key] += 20;
            haveYFields = true;
          };
        };
        this.coordinateChecked = (haveXFields && haveYFields);

        //字段值判断
        data.forEach((val) => {
          for (let key in val) {
            if (Math.abs(val[key]) == 0) continue;
            if (Math.abs(val[key]) <= 180) {
              if (Math.abs(val[key]) <= 90) {
                xFieldO[key] += 1;
              } else {
                xFieldO[key] += 1.5;
              }
            }
            if (Math.abs(val[key]) <= 90) {
              yFieldO[key] += 1;
            }
          }
        });

        //根据权重排序
        for (let key in xFieldO) {
          xFields.push({
            field: key,
            weights: xFieldO[key]
          });
        }
        for (let key in yFieldO) {
          yFields.push({
            field: key,
            weights: yFieldO[key]
          });
        }

        return {
          xFields: xFields.sort((a, b) => {
            return (b.weights - a.weights)
          }),
          yFields: yFields.sort((a, b) => {
            return (b.weights - a.weights)
          })
        }
      }
    },

    created() {
      Bus.$off('field-name-change');
      Bus.$on('field-name-change', (idx, val) => {
        this.fields[idx] = val;
        this.nextInvalid = false;
      });

      Bus.$off('field-type-change');
      Bus.$on('field-type-change', (idx, val) => {
        this.fieldTypes[idx] = val;
        // console.log(this.selectedFile);
      });

      Bus.$off('duplicate-column-name');
      Bus.$on('duplicate-column-name', () => {
        this.nextInvalid = true;
      });
    }
  }

</script>

<style lang="scss" rel="stylesheet/scss">
  @import "common";
  $spaceHeight: 52px;

  .data-upload-preview-wrapper {
    height: 100%;
    width: 100%;
    left: 0;
    top: $spaceHeight;
    z-index: 99;
    position: absolute;
    background-color: rgba($color: #000000, $alpha: 0.5);

    .dialog {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
      background-color: white;

      .title {
        height: 36px;
        padding: 12px;
        font-size: 14px;
        background-color: white;
        font-weight: bold;

        .close-icon {
          position: absolute;
          right: 12px;
          top: 12px;
          cursor: pointer;

          >i {
            font-size: 20px;
          }
        }
      }

      .toolbar {
        height: 32px;
        width: 100%;
        position: absolute;
        left: 0px;
        bottom: 76px;
        z-index: 11;
        text-align: center;

        .encoding-select-wrapper {
          position: absolute;
          top: 4px;
          left: 140px;

          .encoding-select {
            width: 120px;
            text-align: left;
            display: inline-block;

            i {
              color: $gray;
              margin-top: -1px;
            }
          }
        }

        .tip-wrapper {
          position: absolute;
          left: 12px;
          top: 8px;

          >span {
            color: $primary;
          }
        }

        .back-wrapper {
          position: absolute;
          top: 2px;
          left: calc(100% - 170px);
        }

        .next-wrapper {
          position: absolute;
          top: 2px;
          left: calc(100% - 80px);
          display: inline-block;
        }

      }
    }


  }

  .loading-wrapper {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 13;

    .loading {
      position: absolute;
      height: 22px;
      width: 20px;
      left: 0;
      right: 0;
      top: -140px;
      bottom: 0;
      margin: auto;
      z-index: 13;

      >i {
        color: #889;
        font-size: 20px;
      }
    }
  }

  .data-upload-preview-wrapper-coordinate {
    top: $spaceHeight;
    height: calc(100% - $spaceHeight) !important;

    .space-field-wrapper {
      display: inline-block;
      width: 100%;
      height: $spaceHeight;
      top: -$spaceHeight;
      position: absolute;

      .coordinate-type {
        margin: 16px 12px;
      }

      //   .coordinate-type {
      //     vertical-align: center;
      //     height: $spaceHeight;
      //     display: flex;
      //     align-items: center;

      //     input {
      //       margin: 8px;
      //       position: relative;
      //       top: -1px;
      //     }

      //     label {
      //       padding-right: 12px;
      //       line-height: 32px;
      //     }
      //   }

      .coordinate-type-select {

        position: absolute;
        // right: 22px;
        left: 140px;
        bottom: -4px;

        label {
          display: inline-block;
          text-align: center;
          padding: 0 8px;
          line-height: 60px;
          vertical-align: top;
          font-size: 12px;
        }

        .fields-select {
          width: 120px;
          text-align: left;
          display: inline-block;
          padding-top: 16px;
        }
      }

    }
  }

  .toolbar-low {
    bottom: 76px !important;
  }

</style>
